import { useState, useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
import { Link, useNavigate } from "react-router-dom";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { LogicalSize } from '@tauri-apps/api/dpi';
import { homeDir } from "@tauri-apps/api/path";
import { UserInterface, RouteInfo } from "./UserInterface.tsx";
import "./LogIn.css";

function LogIn() {
  const [password, setPassword] = useState("");
  const [username, setUsername] = useState("");
  const navigate = useNavigate();
  const { 
    mongoDBUrl, setMongoDBUrl,
   } = UserInterface();

  useEffect(() => {
    sessionStorage.setItem('login-response', "");
    getCurrentWindow().setSize(new LogicalSize(800, 600));
  },[]);

  const login = async(user_and_url : RouteInfo)=> {
    try{
      const response = await invoke<string>("login", {
        user : user_and_url.user,
        mongodbUrl : user_and_url.url
      })  
      // console.log("login response is ", response);
      sessionStorage.setItem('login-response', response);
    }catch(error){
      sessionStorage.setItem('login-response', String(error));
    }
    window.dispatchEvent(new Event('storage'));
    // 触发事件
  }

  const handleSubmit = async(e: { preventDefault: () => void; }) => {
    e.preventDefault();
    try{
      const user = {
        username : username,
        password : password,
      }
      const route_info = {
          user: user,
          url: mongoDBUrl
      }
      login(route_info);
      const home = await homeDir();
      navigate("/files", { 
        state : { 
          path : home,
          routeInfo: route_info,
        }
      });
    } catch(error){
      console.error(error);
    }
  };

  return (
    <main className="container">
      <h1 id="logintext">😁Log In</h1>
      <form onSubmit={handleSubmit}>
        <input id="input-username"
          onChange={(e) => setUsername(e.currentTarget.value)}
          type="text"
          placeholder="😃Enter username"
          value={username}
        />
        <input id="input-password" 
        onChange={(e) => setPassword(e.currentTarget.value)} 
        type="password" 
        placeholder="😆Enter password" 
        value={password}
        />
        <input id="input-mongodb-url"
          onChange={(e) => setMongoDBUrl(e.currentTarget.value)}
          type="text"
          placeholder="😇Enter MongoDB URL"
          value={mongoDBUrl}
          required
        />
        <div className="button-container">
          <button type="submit" id="LogIn-button">
            😉Log In
          </button>
          <Link to="/register">
            <button type="submit" id="Register-button">
              🙃Register
            </button>
          </Link>
        </div>
      </form>
    </main>
  );
}

export default LogIn;
